<template>
  <div class="app-container">
    <!-- 搜索和添加 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.keyword"
        placeholder="用户名/昵称"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        v-if="$hasButton('add')"
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        添加
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" width="70" align="center">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="用户名" prop="username" />
      <el-table-column label="昵称" prop="nickName" />
      <el-table-column label="邮箱" prop="email" />
      <el-table-column label="头像" width="110" align="center">
        <template slot-scope="scope">
          <img
            :src="scope.row.avatar"
            style="width: 50px; height: 50px; border-radius: 50%"
          />
        </template>
      </el-table-column>
      <el-table-column label="状态" width="110" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="170" align="center">
        <template slot-scope="scope">
          {{ scope.row.gmtCreate }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10]"
        layout="total, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="80px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="temp.username"
            :disabled="!isAdmin && dialogStatus === 'update'"
            @blur="checkUsernameForUpdate"
          />
          <span v-if="usernameExists" style="color: red">用户名已存在</span>
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="temp.nickName" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="temp.email" />
        </el-form-item>
        <el-form-item label="角色" prop="roleName">
          <el-select v-model="temp.roleName" placeholder="请选择角色">
            <el-option
              v-for="role in roles"
              :key="role.id"
              :label="role.roleName"
              :value="role.roleName"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
          v-if="dialogStatus === 'create'"
        >
          <el-input v-model="temp.password" type="password" />
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :action="uploadAction"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="temp.avatar" :src="temp.avatar" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import userApi from "@/api/acl/admin";
import Pagination from "@/components/Pagination";
import { getToken } from "@/utils/auth";

export default {
  name: "UserList",
  components: { Pagination },
  data() {
    return {
      list: [],
      roles: [],
      currentPage: 1,
      pageSize: 10,
      BASE_API: process.env.BASE_API || "http://localhost:9001",
      uploadHeaders: {
        Authorization: getToken(),
      },
      listQuery: {
        keyword: "",
      },
      total: 0,
      listLoading: true,
      checkingUsername: false,
      usernameExists: false,
      selectedUsers: [],
      dialogVisible: false,
      dialogStatus: "",
      dialogTitle: "",
      temp: {
        id: undefined,
        username: "",
        nickName: "",
        password: "",
        avatar: "",
        email: "",
        status: 1,
        roleName: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        nickName: [{ required: true, message: "请输入昵称", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        email: [
          { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
        ],
        roleName: [
          { required: true, message: "请选择角色", trigger: "change" },
        ],
      },
    };
  },
  computed: {
    uploadAction() {
      return `${this.BASE_API}/eduoss/fileoss`;
    },
    isAdmin() {
      return (
        this.$store.getters.roles && this.$store.getters.roles.includes("admin")
      );
    },
  },
  created() {
    // 先加载角色数据，再加载用户列表
    this.fetchRoles().then(() => {
      this.getList();
    });
  },
  methods: {
    getList() {
      this.listLoading = true;
      userApi
        .getUserList(this.currentPage, this.pageSize, this.listQuery.keyword)
        .then((response) => {
          this.list = (response.data && response.data.items) || [];
          this.total = (response.data && response.data.total) || 0;
        })
        .catch((error) => {
          console.error("获取用户列表失败:", error);
          this.list = [];
          this.total = 0;
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.getList();
    },
    fetchRoles() {
      return userApi.getAllRoles().then((response) => {
        this.roles = response.data.items || [];
        return this.roles;
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleSelectionChange(val) {
      this.selectedUsers = val;
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        username: "",
        nickName: "",
        password: "",
        avatar: "",
        email: "",
        status: 1,
        roleName: "管理员",
      };
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogTitle = "添加用户";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    checkUsernameForUpdate() {
      if (this.temp.username && this.dialogStatus === "update") {
        this.checkUsername();
      }
    },
    async checkUsername() {
      if (!this.temp.username) return;

      this.checkingUsername = true;
      try {
        const res = await userApi.checkUsername(this.temp.username);
        this.usernameExists = res.data.exists;
      } catch (error) {
        console.error("检查用户名失败:", error);
      } finally {
        this.checkingUsername = false;
      }
    },
    createData() {
      this.$refs["dataForm"].validate(async (valid) => {
        if (valid) {
          try {
            // 先检查用户名是否存在
            const res = await userApi.checkUsername(this.temp.username);
            if (res.data.exists) {
              this.$message.error("用户名已存在");
              return;
            }

            // 用户名不存在，继续创建
            const response = await userApi.addUser(this.temp);

            if (this.temp.roleName) {
              const role = this.roles.find(
                (r) => r.roleName === this.temp.roleName
              );
              if (role) {
                await userApi.assignRoles(response.data.id, [role.id]);
              }
            }

            this.getList();
            this.dialogVisible = false;
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 2000,
            });
          } catch (error) {
            console.error("检查用户名失败:", error);
            this.$message.error("操作失败，请重试");
          }
        }
      });
    },
    handleUpdate(row) {
      console.log("编辑用户:", row);
      this.temp = Object.assign({}, row);
      this.dialogStatus = "update";
      this.dialogTitle = "编辑用户";
      this.dialogVisible = true;

      // 确保角色数据已加载
      this.fetchRoles().then(() => {
        userApi
          .getRoleIdsByUserId(row.id)
          .then((response) => {
            console.log("角色ID响应:", response);
            const roleIds = response.data.items || [];
            console.log("用户角色IDs:", roleIds);
            console.log("可用角色列表:", this.roles);

            if (roleIds.length > 0 && this.roles.length > 0) {
              // 确保ID类型一致 - 都转为字符串比较
              const role = this.roles.find((r) =>
                roleIds.some((id) => String(id) === String(r.id))
              );

              if (role) {
                this.$set(this.temp, "roleName", role.roleName);
                console.log("设置角色名:", role.roleName);
              } else {
                console.warn("未找到匹配的角色:", roleIds, this.roles);
              }
            }
          })
          .catch((error) => {
            console.error("获取用户角色失败:", error);
          });
      });

      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    confirmUsernameChange() {
      this.$confirm("修改用户名将影响用户登录，确定要继续吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.updateData();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          const submitData = {
            id: this.temp.id,
            username: this.temp.username,
            nickName: this.temp.nickName,
            email: this.temp.email,
            avatar: this.temp.avatar,
            status: this.temp.status,
          };

          // 先检查用户名是否修改
          const originalUser = this.list.find((u) => u.id === this.temp.id);
          if (originalUser.username !== this.temp.username) {
            if (!this.isAdmin) {
              this.$message.error("只有管理员可以修改用户名");
              return;
            }
            // 用户名有修改，先检查
            userApi.checkUsername(this.temp.username).then((res) => {
              if (res.data.exists) {
                this.$message.error("用户名已存在");
              } else {
                this.updateUserAndRole(submitData);
              }
            });
          } else {
            // 用户名未修改，直接更新
            this.updateUserAndRole(submitData);
          }
        }
      });
    },
    updateUserAndRole(userData) {
      // 1. 更新用户基本信息
      userApi
        .updateUser(userData)
        .then(() => {
          // 2. 更新用户角色
          const role = this.roles.find(
            (r) => r.roleName === this.temp.roleName
          );
          if (role) {
            return userApi.assignRoles(userData.id, [role.id]);
          }
          return Promise.resolve();
        })
        .then(() => {
          this.getList(); // 刷新列表
          this.dialogVisible = false;
          this.$notify({
            title: "成功",
            message: "更新成功",
            type: "success",
            duration: 2000,
          });
        })
        .catch((error) => {
          this.$message.error(error.message || "更新失败");
        });
    },
    doUpdate(submitData) {
      userApi
        .updateUser(submitData)
        .then(() => {
          this.getList(); // 刷新列表
          this.dialogVisible = false;
          this.$notify({
            title: "成功",
            message: "更新成功",
            type: "success",
            duration: 2000,
          });
        })
        .catch((error) => {
          this.$message.error(error.message || "更新失败");
        });
    },
    handleDelete(row) {
      this.$confirm("确认删除该用户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        userApi.deleteUser(row.id).then(() => {
          const index = this.list.findIndex((v) => v.id === row.id);
          this.list.splice(index, 1);
          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
            duration: 2000,
          });
        });
      });
    },
    handleStatusChange(row) {
      const text = row.status === 1 ? "启用" : "停用";
      this.$confirm(`确认要${text}该用户吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          userApi.updateUser(row).then(() => {
            this.$notify({
              title: "成功",
              message: `${text}成功`,
              type: "success",
              duration: 2000,
            });
          });
        })
        .catch(() => {
          row.status = row.status === 1 ? 0 : 1;
        });
    },
    handleAvatarSuccess(res, file) {
      if (res && res.code === 200) {
        this.temp.avatar = res.data.url;
        this.$message.success("头像上传成功");
      } else {
        this.$message.error(res.message || "头像上传失败");
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isJPG && !isPNG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
      if (!isLt5M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return (isJPG || isPNG) && isLt5M;
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: center;
}
</style> 